#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <string.h>

typedef float (*operation) (float a, float b);

float read_num (char *prompt);
float plus (float a, float b);
float minus (float a, float b);
float multiply (float a, float b);
float devide (float a, float b);
operation read_operation (void);
void print_select_list (void);

int
main ()
{
  operation op = NULL;
  float n1 = 0;
  float n2 = 0;
  float result = 0;
  do
    {
      print_select_list ();
      op = read_operation ();
    }
  while (op == NULL);

  n1 = read_num ("Input a number: ");
  n2 = read_num ("Input a number: ");
  result = (*op) (n1, n2);
  printf ("Result: %.3f\n", result);
  return EXIT_SUCCESS;
}

float
read_num (char *prompt)
{
  char buf[10];
  char *endptr = NULL;
  float val;
  int last;
  while (1)
    {
      printf ("%s", prompt);
      fgets (buf, sizeof (buf), stdin);
      last = strlen (buf) - 1;
      if (buf[last] == '\n')
	{
	  buf[last] = '\0';
	}
      val = strtod (buf, &endptr);
      if (endptr != NULL && *endptr != '\0')
	{
	  printf ("%s is not a valid number.\n", buf);
	}
      else
	{
	  return val;
	}
    }
}

void
print_select_list ()
{
  printf ("Select a operation\n");
  printf ("1 Plus\n");
  printf ("2 Minus\n");
  printf ("3 Multiply\n");
  printf ("4 Devide\n");
}

operation
read_operation ()
{
  int index = 0;
  index = (int) read_num ("Your selection is: ");
  switch (index)
    {
    case 1:
      return plus;
    case 2:
      return minus;
    case 3:
      return multiply;
    case 4:
      return devide;
    }
  return NULL;
}


float
plus (float a, float b)
{
  return a + b;
}

float
minus (float a, float b)
{
  return a - b;
}

float
multiply (float a, float b)
{
  return a * b;
}

float
devide (float a, float b)
{
  return a / b;
}
